package com.zsj.juc.completableFuture;

import java.util.concurrent.*;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/4/18 18:37
 * @description 为Future接口的升级
 */
public class CompletableFutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*
        CompletionStage 这个接口 代表阶段状态

        核心静态方法 4个

        如果未指定线程池参数  默认为
       public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return asyncSupplyStage(ASYNC_POOL, supplier);
        }

        public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                Executor executor) {
            return asyncSupplyStage(screenExecutor(executor), supplier);
        }

        public static CompletableFuture<Void> runAsync(Runnable runnable) {
            return asyncRunStage(ASYNC_POOL, runnable);
        }


        public static CompletableFuture<Void> runAsync(Runnable runnable,
                Executor executor) {
            return asyncRunStage(screenExecutor(executor), runnable);
        }
         */

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        //无返回值的
        /*CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, threadPool);
        System.out.println(completableFuture.get());*/

        //有返回值的
        CompletableFuture<Object> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "supplyAsync";
        }, threadPool);
        System.out.println(completableFuture.get());
        threadPool.shutdown();
    }
}
